<script lang="ts" setup>
  import { ref, onMounted, onUnmounted } from 'vue';
  import * as echarts from 'echarts/core';
  const props = defineProps({
    data1: { type: Object as () => any, required: true },
    data2: { type: Object as () => any, default: () => [] },
    data3: { type: Object as () => any, default: () => [] },
    legendName: { type: Object as () => any, default: () => [] },
    dataName: { type: Object as () => any, default: () => [] },
    datax: { type: Object as () => any, required: true },
  });

  const chartRef = ref<HTMLElement | null>(null);
  let chartInstance: echarts.ECharts | null = null;

  const option: any = {
    legend: {
      data: [], // 图例数据项名称，应与series中的data项名称对应
      textStyle: {
        fontSize: '10px',
        color: '#fff',
      },
      top: 10,
    },
    graphic: [
      {
        type: 'text',
        bottom: 20, // 距离底部的固定距离
        right: 10, // 距离底部的固定距离
        style: {
          text: props.dataName[0], // X轴名称
          fill: '#fff',
          fontSize: 10,
          align: 'center',
        },
      },
    ],
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        // type: 'cross',
        label: { color: '#fff' },
        crossStyle: { color: '#6d7882' },
      },
    },
    grid: {
      left: '5%',
      right: '7%',
      bottom: '10%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: props.datax,
      splitLine: { show: false },
      axisLine: {
        show: true, // 确保显示轴线
        lineStyle: {
          color: '#fff', // 轴线颜色
          width: 1, // 轴线宽度
          type: 'solid', // 线型（solid实线，dashed虚线）
        },
      },
    },
    yAxis: {
      type: 'value',
      name: props.dataName[1],
      scale: true, //纵坐标自适应
      splitLine: {
        show: false,
      },
      axisLine: {
        show: true, // 确保显示轴线
        lineStyle: {
          color: '#fff', // 轴线颜色
          width: 1, // 轴线宽度
          type: 'solid', // 线型（solid实线，dashed虚线）
        },
      },
    },
    series: [
      {
        name: props.legendName[0] ?? '',
        nameTextStyle: {
          fontSize: '18px',
          color: 'red', // 设置 y 轴名称的颜色为红色
        },
        data: props.data1,
        type: 'line',
        smooth: false,
        lineStyle: {
          width: 1,
          color: 'rgb(160, 207, 255)',
        },
        areaStyle: {
          opacity: 0.8,
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(160, 207, 255, 0.8)' },
            { offset: 1, color: 'rgba(160, 207, 255, 0.1)' },
          ]),
        },
        symbolSize: 1,
        symbol: 'circle',
      },
    ],
  };

  const initCharts = () => {
    try {
      if (props.data2.length > 0) {
        option.series[1] = {
          name: props.legendName[1] ?? '',
          data: props.data2,
          type: 'line',
          smooth: false,
          lineStyle: {
            width: 1,
            color: 'rgb(179, 225, 157)',
          },
          areaStyle: {
            opacity: 0.8,
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(179, 225, 157, 0.8)' },
              { offset: 1, color: 'rgba(179, 225, 157, 0.1)' },
            ]),
          },
          symbolSize: 1,
          symbol: 'circle',
        };
      } else {
        if (option.series[1]) delete option.series[1];
      }
      if (props.data3.length > 0) {
        option.series[2] = {
          name: props.legendName[2] ?? '',
          data: props.data3,
          type: 'line',
          smooth: false,
          lineStyle: {
            width: 1,
            color: 'rgb(243, 209, 158)',
          },
          areaStyle: {
            opacity: 0.8,
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(243, 209, 158, 0.8)' },
              { offset: 1, color: 'rgba(243, 209, 158, 0.1)' },
            ]),
          },
          symbolSize: 1,
          symbol: 'circle',
        };
      } else {
        if (option.series[2]) delete option.series[2];
      }
      option.legend.data = props.legendName ?? [];
      option.series[0].data = props.data1 ?? [];
      option.xAxis.data = props.datax ?? [];
      if (chartRef.value && !chartInstance) {
        chartInstance = echarts.init(chartRef.value);
        chartInstance?.setOption(option, true);
      }
    } catch (error) {
      console.error('图表初始化失败:', error);
    }
  };

  const updateChart = () => {
    try {
      if (props.data2.length > 0) {
        option.series[1] = {
          name: props.legendName[1] ?? '',
          data: props.data2,
          type: 'line',
          smooth: false,
          lineStyle: {
            width: 1,
            color: 'rgb(179, 225, 157)',
          },
          areaStyle: {
            opacity: 0.8,
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(179, 225, 157, 0.8)' },
              { offset: 1, color: 'rgba(179, 225, 157, 0.1)' },
            ]),
          },
          symbolSize: 1,
          symbol: 'circle',
        };
      } else {
        if (option.series[1]) delete option.series[1];
      }
      if (props.data3.length > 0) {
        option.series[2] = {
          name: props.legendName[2] ?? '',
          data: props.data3,
          type: 'line',
          smooth: false,
          lineStyle: {
            width: 1,
            color: 'rgb(243, 209, 158)',
          },
          areaStyle: {
            opacity: 0.8,
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(243, 209, 158, 0.8)' },
              { offset: 1, color: 'rgba(243, 209, 158, 0.1)' },
            ]),
          },
          symbolSize: 1,
          symbol: 'circle',
        };
      } else {
        if (option.series[2]) delete option.series[2];
      }
      option.legend.data = props.legendName ?? [];
      option.series[0].data = props.data1 ?? [];
      option.xAxis.data = props.datax ?? [];
      if (chartRef.value && chartInstance) {
        chartInstance.setOption(option, true);
      }
    } catch (error) {
      console.error('图表初始化失败:', error);
    }
  };

  onMounted(() => {
    // 确保在 DOM 加载完成后更新图表
    setTimeout(() => {
      initCharts();
    }, 100);

    // 添加窗口大小变化监听
    window.addEventListener('resize', updateChart);
  });

  onUnmounted(() => {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', updateChart);
    chartInstance?.dispose();
  });

  watch(
    () => [props.datax, props.data1],
    () => updateChart(),
    { deep: true }
  );

  defineExpose({
    updateChart, // 暴露方法到父组件
    chartRef,
  });
</script>
<template>
  <div ref="chartRef" class="chart-container"></div>
</template>

<style scoped>
  .chart-container {
    width: 100%;
    height: 100%;
  }
</style>
